package com.zhanggm.zyk.fujian.controller;


import com.bw.springboot.starter.upload.model.Chunk;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import com.bw.zhanggm.file.config.AjaxResult;
import com.zhanggm.zyk.fujian.entity.Fujian;
import com.zhanggm.zyk.fujian.service.IFujianService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-03-12
 */
@Slf4j
@RestController
@RequestMapping("/fujian")
public class FujianController {

    @Autowired
    FileService fileService;

    @Autowired
    IFujianService iFujianService;

    /**
     * 文件查询接口
     * 远程调用该接口
     * @param id
     * @return
     */
    @GetMapping("getById")
    public Fujian getById(@RequestParam("id") Integer id) {
        return iFujianService.getById(id);
    }


    /**
     * 文件上传合并接口
     * @param chunk
     * @return
     * @throws InterruptedException
     */
    @PostMapping("upload")
    public AjaxResult upload(@ModelAttribute Chunk chunk) throws InterruptedException {
        fileService.postFileUpload(chunk);
        if (chunk.getChunkNumber().equals(chunk.getTotalChunks())) {
            log.info("开始合并文件");
            TimeUnit.SECONDS.sleep(1);
            FileResult fileResult = fileService.mergeFile(chunk);
            //保存文件表
            Fujian fujian = new Fujian().setFileName(fileResult.getFileUrl());
            iFujianService.save(fujian);
            return AjaxResult.success(fujian.getId());
        }
        return AjaxResult.success();
    }

}
